package com.monster.starter.mybatis.plus.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.monster.utils.TimeUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Component;

/**
 * 实体自动注入
 *
 * @author kuang
 */
@Component
@ConditionalOnClass(MybatisPlusInterceptor.class)
public class MonsterBaseEntityMetaObjectHandler implements MetaObjectHandler {
    /**
     * 获取用户信息
     */
    @Autowired(required = false)
    private UserService userService;

    /**
     * 获取用户信息
     * @return
     */
    private String getUser () {
        if (userService == null) {
            return "";
        }
        return userService.get();
    }
    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject.hasSetter("createTime")) {
            // 创建时间
            this.strictInsertFill(metaObject, "createTime", () -> Long.valueOf(TimeUtils.format(TimeUtils.yyyyMMddHHmmssSSS)), Long.class);
        }
        if (metaObject.hasSetter("createUser")) {
            // 创建人
            this.strictInsertFill(metaObject, "createUser", this::getUser, String.class);
        }
        if (metaObject.hasSetter("dataStatus")) {
            // 数据状态
            this.strictInsertFill(metaObject, "dataStatus", () -> 1, Integer.class);
        }
        if (metaObject.hasSetter("version")) {
            // 数据版本
            this.strictInsertFill(metaObject, "version", () -> 1L, Long.class);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.hasSetter("updateTime")) {
            // 修改时间
            this.strictUpdateFill(metaObject, "updateTime", () -> Long.valueOf(TimeUtils.format(TimeUtils.yyyyMMddHHmmssSSS)), Long.class);
        }
        if (metaObject.hasSetter("updateUser")) {
            // 修改人
            this.strictUpdateFill(metaObject, "updateUser", this::getUser, String.class);
        }
    }
}
